import { defineStore } from 'pinia';
import { getCache, removeCache, setCache } from '@/utils/cache';
import { TOKEN_KEY, CITY_KEY, USER_INFO_KEY, USERID_KEY, OPENID_KEY } from '@/enums/cacheEnum';
import { wmaLogin, userGet, smsLogin, authLogout } from '@/services/api/auth';

interface AuthState {
    token?: string;
    userId?: number | null;
    openId?: number | null;
    userInfo?: object;
    city?: string;
    height?: number;
    historicalSearch?: any[];
    orderGoods?: any[];
}

export const useAuthStore = defineStore({
    id: 'auth',
    state: (): AuthState => ({
        token: getCache(TOKEN_KEY) || undefined,
        userId: getCache(USERID_KEY) || null,
        openId: getCache(OPENID_KEY) || null,
        userInfo: getCache(USER_INFO_KEY) || {},
        city: getCache(CITY_KEY) || undefined,
        height: 0, //页面高度
        historicalSearch: [],
        orderGoods: [], //订单数据
    }),
    getters: {
        getToken: (state) => state.token,
        getUserId: (state) => state.userId,
        getOpenId: (state) => state.openId,
        getUserInfo: (state) => state.userInfo,
        getAuthorization: (state) => {
            return state.token ? state.token : {};
        },
        getCity: (state) => state.city,
        getHeight: (state) => state.height,
        getHistoricalSearch: (state) => state.historicalSearch,
        getOrderGoods: (state) => state.orderGoods,
    },
    actions: {
        initToken() {
            this.token = getCache<string>(TOKEN_KEY) || undefined;
        },

        setToken(token: string | undefined) {
            setCache(TOKEN_KEY, token);
            this.token = token;
        },
        setUserId(userId: number | null) {
            setCache(USERID_KEY, userId);
            this.userId = userId;
        },
        setOpenId(openId: number | null) {
            console.log(openId, 111);
            setCache(OPENID_KEY, openId);
            this.openId = openId;
        },
        setUserInfo(userInfo: object) {
            setCache(USER_INFO_KEY, userInfo);
            this.userInfo = userInfo;
        },
        setCity(data: string | undefined) {
            setCache(CITY_KEY, data);
            this.city = data;
        },
        setHeight(data: number | undefined) {
            console.log(data);
            this.height = data;
        },
        setHistoricalSearch(data: number | undefined) {
            this.historicalSearch = data;
        },
        setOrderGoods(data: any[]) {
            this.orderGoods = data;
        },
        /**
         * @description 登录 type=1小程序登录  2验证码登录
         */
        async login(data: any, type: number): Promise<any> {
            try {
                if (type == 1) {
                    const res = await wmaLogin(data);
                    this.setToken(res.data.accessToken);
                    this.setUserId(res.data.userId);
                    this.setOpenId(res.data.openid);
                } else if (type == 2) {
                    const res = await smsLogin(data);
                    this.setToken(res.data.accessToken);
                    this.setUserId(res.data.userId);
                    this.setOpenId(res.data.openid);
                }
                return Promise.resolve();
            } catch (err: any) {
                return Promise.reject(err);
            }
        },
        /**
         * @description 获取用户信息
         */
        async getUserInfos(): Promise<any> {
            try {
                const res = await userGet();
                this.setUserInfo(res.data);
                return Promise.resolve(res.data);
            } catch (err: any) {
                return Promise.reject(err);
            }
        },
        /**
         * @description 判断是否登录
         */
        async isLogin(): Promise<any> {
            try {
                if (!this.getToken) {
                    uni.navigateTo({
                        url: '/pages/login/index',
                    });
                }
                return Promise.resolve(this.getToken ? true : false);
            } catch (err: any) {
                return Promise.reject(err);
            }
        },
        /**
         * @description 登出
         */
        async loginOut(): Promise<any> {
            try {
                const res = await authLogout();
                removeCache(TOKEN_KEY);
                this.setToken(undefined);
                this.setUserId(null);
                this.setUserInfo({});
                // uni.switchTab({
                //     url: '/pages/login/index',
                // }); 
				 uni.reLaunch({
                    url: '/pages/login/index',
                });
                return Promise.resolve(res);
            } catch (err: any) {
                return Promise.reject(err);
            }
        },
        /**
         * @description 刷新token
         */
        // async refreshToken(): Promise<LoginModel> {
        //     try {
        //         const { data } = await refreshToken();
        //         this.setToken(data.token);
        //         return Promise.resolve(data);
        //     } catch (err: any) {
        //         return Promise.reject(err);
        //     }
        // },
    },
});
